import re
import pandas as pd
from config import shangyao_config
import warnings
import os
from config.excel_config import column_name
from utils.file_utils import delete_file
from utils import clean_utils
from h3yun.service.sales_data_service import upload_day_sales_data
from clean_data.common.mateGoodsAndYYMC import mate_CPMC, mate_YYMC
from config.excel_config import shangyao_column_types
warnings.filterwarnings('ignore')


# 出库日期  -> 出库时间C2
# 品名-规格-产地 -> 配送商备案产品I2 / 生产厂家J2
# 客户名称 -> 医院名称L2
# 出库数量 -> 数量U2
# 批号 -> 批次信息AD2
# 含税单价 -> 单价V2
# 库存拥有者 ->  配送商H2
def clean_data():
    file_list = os.listdir(shangyao_config.download_file_prefix)
    file_list.sort(reverse=True)
    if len(file_list) > 0:
        file = file_list[0]
    else:
        return
    full_file_path = os.path.join(shangyao_config.download_file_prefix+f"\\{file}")
    print(full_file_path)
    df = pd.read_excel(full_file_path, dtype=shangyao_column_types)
    df = df.fillna('')
    temp_list = df['品名-规格-产地']
    PACP = []
    SCCJ = []
    for temp in temp_list:
        PACP.append(re.split(r'-(?=\d)', temp)[0])
        t = str(temp).split('-')
        SCCJ.append(t[len(t)-1])
    temp_list = df['出库日期']
    id_list = clean_utils.get_ids(shangyao_config.id_prefix, temp_list.tolist())

    df['数据来源'] = shangyao_config.data_source
    CPMC, CPBM_PSS, CPBM_GSNB = mate_CPMC(df['商品编码'], '上药康德乐合丹（深圳）医药有限公司')
    YYMC, YYBM_PSS, YYBM_GSNB = mate_YYMC(df['客户编码'], '上药康德乐合丹（深圳）医药有限公司')
    data = {
        column_name['ID']: id_list,
        column_name['CKSJ']: df['出库日期'],
        column_name['PSS']: df['库存拥有者'],
        column_name['PSS_BACP']: CPMC,
        column_name['CPBM_PSS']: CPBM_PSS,
        column_name['CPBM_GSNB']: CPBM_GSNB,
        column_name['SCCJ']: SCCJ,
        column_name['YYMC']: YYMC,
        column_name['KHBM']: YYBM_PSS,
        column_name['YYBM']: YYBM_GSNB,
        column_name['SL']: df.filter(like='出库数量').iloc[:, 0],
        column_name['DJ']: df['含税单价'],
        column_name['PCXX']: df['批号'],
        column_name['SJLY']: df['数据来源']
    }
    df = pd.DataFrame(data)

    save_file_path = f'{shangyao_config.clean_file_prefix}\\{file}'
    delete_file(save_file_path)
    df.to_excel(save_file_path, index=False)

    # 上传到氚云上面
    upload_day_sales_data(save_file_path)


if __name__ == '__main__':
    clean_data()